const app = require('express')();
const express = require('express');
//加载环境变量
require('dotenv').config({ path: `.env.${process.env.NODE_ENV}` });
// 引入路径别名插件工具支持
require('module-alias/register');
const {getIP} = require('@/appBoot/index');
const routes = require('@/router/index');
routes(app); 

// 引入文件上传
const upload = require('@/client/multerConfig');

const responseHandler = require('@/middlewares/responseMiddleware');// 引入自定义的中间件
const authMiddleware = require('@/middlewares/authMiddleware');// 引入验证 token 的中间件
const catchErrorMiddleware = require('@/middlewares/catchErrorMiddleware');// 引入全局错误处理中间件
const logMiddleware = require('@/middlewares/logMiddleware');// 引入全局日志中间件

app.use(express.json()); // 用于解析JSON格式的请求体
app.use(express.urlencoded({ extended: true })); // 用于解析URL编码的请求体


// 使用自定义的中间件来设置日志记录
logMiddleware(app);

// 引入自定义的响应处理数据结构的中间件
app.use(responseHandler);

app.get("/", (req, res, next) => {
    res.send("<h1>hello world!  </h1>")
})

app.use('/static', express.static('public'))
app.post('/upload', upload.single('file'), (req, res) => {
    const fileUrl = `http://${getIP()}:${process.env.PORT}/static/${req.file.filename}`;
    res.createResponse(200,'success',{name: req.file.filename,url: fileUrl })
},(err, req, res, next) => {
    if(err) res.createResponse(500,'上传失败'+err)
});



// 错误处理中间件
app.use(catchErrorMiddleware);

app.use("*", (req, res, next) => {
    res.end("404")
})

app.listen(process.env.PORT, () => console.log(`${process.env.APPNAME}服务器启动成功!  ${getIP()}:${process.env.PORT}`));

